from project.models import Project, ProjectRole, Participate
from user.models import User
from pms.common.utils import flatten_view
from django.db.models import Model
from pms.common.views import PermissionDeny


def project_add_member(project, user, rid, view):
    assert isinstance(project, Project)
    assert isinstance(user, User)
    project_role = ProjectRole.objects.get(id=rid)
    assert project_role.pid == project  # 项目身份要项目控制项目
    argv = flatten_view(view, {
        'annotation': 'annotation'
    })
    new_participate = Participate(uid=user, rid=project_role, **argv)
    new_participate.save()
    return new_participate.rid.pid, new_participate.uid


def project_update_member(project, user, view):
    assert isinstance(project, Project)
    assert isinstance(user, User)
    participate = Participate.objects.get(uid=user, rid__pid=project)
    argv = flatten_view(view, {
        'rid_id': ['role', 'id'],
        'annotation': 'annotation'
    })
    if 'rid_id' in argv:
        assert ProjectRole.objects.get(id=argv['rid_id']).pid == project
    participate.__dict__.update(**argv)
    participate.save()
    return participate.rid.pid, participate.uid


def project_delete_member(project, user):
    assert isinstance(project, Project)
    assert isinstance(user, User)
    participate = Participate.objects.get(uid=user, rid__pid=project)
    participate.delete()
    return True


def assert_member_of(user, project):
    """ 断言 user 是 project 的成员，并返回参与关系。否则抛出 PermissionDeny """
    try:
        return Participate.objects.get(uid=user, rid__pid=project)
    except Participate.DoesNotExist:
        raise PermissionDeny
